package excel

import (
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gtime"
	"github.com/xuri/excelize/v2"
	"io"
	"strings"
)

// 导出数据
func Export(r *ghttp.Response, data [][]interface{}, header []interface{}, filename string, suffix string) error {
	if data == nil || header == nil {
		return nil
	}

	if filename == "" {
		filename = gtime.TimestampStr()
	}

	// 新建文件
	f := excelize.NewFile()
	sheet1 := f.GetSheetName(0)

	// 流式写入器
	streamWriter , err := f.NewStreamWriter(sheet1)
	if err != nil {
		return err
	}
	err = streamWriter.SetRow("A1", header)
	if err != nil {
		return err
	}

	// 插入行数据
	column := 2
	for _, v := range data {
		cell, _ := excelize.CoordinatesToCellName(1, column)
		_ = streamWriter.SetRow(cell, v)
		column++
	}

	_ = streamWriter.Flush()

	switch suffix {
	case "xlsx":
		r.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8;")
		r.Header().Add("Content-Disposition", "inline; filename="+ filename +".xlsx")
		r.Header().Add("Cache-Control", "max-age=0")
		break
	case "xls":
		r.Header().Add("Content-Type", "application/vnd.ms-excel;charset=utf-8")
		r.Header().Add("Content-Disposition", "inline; filename="+ filename +".xls")
		r.Header().Add("Cache-Control", "max-age=0")
		break
	case "csv":
		r.Header().Add("Content-Type", "text/csv;charset=utf-8;")
		r.Header().Add("Content-Disposition", "attachment; filename="+ filename +".csv")
		r.Header().Add("Cache-Control", "max-age=0")
		break
	case "html":
		r.Header().Add("Content-Type", "text/html;charset=utf-8;")
		r.Header().Add("Content-Disposition", "attachment; filename="+ filename +".html")
		r.Header().Add("Cache-Control", "max-age=0")
		break
	}

	_ = f.Write(r.Writer)
	return nil
}

// 导入
func Import(r io.Reader, start int) ([][]string, error) {
	f, err := excelize.OpenReader(r)
	if err != nil {
		return nil, err
	}

	sheet1 := f.GetSheetName(0)
	rows, err := f.GetRows(sheet1)
	if err != nil {
		return nil, err
	}

	var excelData [][]string
	excelData = excelData
	for k, row := range rows {
		if k >= start - 1 {
			var cellData []string
			var notEmptyCell bool
			for _, cell := range row  {
				if len(strings.Trim(cell, " ")) > 0 {
					notEmptyCell = true
				}
				cellData = append(cellData, cell)
			}
			if notEmptyCell == true {
				excelData = append(excelData, cellData)
			}
		}
	}

	return excelData, nil
}